package com.tmptSource.service.impl;

import com.tmpt.dto.Result;
import com.tmpt.utils.DateTool;
import com.tmpt.service.impl.DataLimitService;
import com.tmpt.utils.StringUtils;
import com.tmptSource.bean.*;
import com.tmptSource.dto.OwPictureMagDto;
import com.tmptSource.enums.OwTaskStatus;
import com.tmptSource.mapper.OwExecuteRecordMapper;
import com.tmptSource.mapper.OwIssueDeclareMapper;
import com.tmptSource.dto.OwIssueDeclareDto;
import com.tmptSource.dto.PageDto;
import com.tmptSource.mapper.OwPictureMagMapper;
import com.tmptSource.mapper.OwTaskMapper;
import com.tmptSource.service.intf.IOwIssueDeclareService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tmptSource.utils.dozer.MyMapper;
import com.tmptSource.utils.page.MyPageUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.dozer.Mapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by wxy on 2016/7/28.
 */
@Service(value="owIssueDeclareService")
@Transactional(propagation = Propagation.REQUIRED)
public class OwIssueDeclareService implements IOwIssueDeclareService {

    private Logger log = Logger.getLogger(this.getClass());
    @Autowired private DataLimitService dataLimitService;
    @Autowired private Mapper mapper;
    @Autowired private MyMapper myMapper;
    @Autowired private MyPageUtils myPageUtils;
    @Autowired
    private OwIssueDeclareMapper owIssueDeclareMapper;
    @Autowired
    private OwPictureMagMapper owPictureMagMapper;
    @Autowired
    private OwExecuteRecordMapper owExecuteRecordMapper;
    @Autowired
    private OwTaskMapper owTaskMapper;



    @Override
    public Result<OwIssueDeclareDto> pagination(OwIssueDeclareDto owIssueDeclareDto,PageDto pageDto) {
        //分页查询
        Result<OwIssueDeclareDto> result = myPageUtils.pagination(
                owIssueDeclareDto,pageDto,
                OwIssueDeclare.class,
                OwIssueDeclareDto.class,
                owIssueDeclareMapper,
                false,null);

        return result;
    }

    @Override
    public Result<OwIssueDeclareDto> paginationWithoutLogin(OwIssueDeclareDto owIssueDeclareDto,PageDto pageDto) {
        //分页查询
        Result<OwIssueDeclareDto> result = myPageUtils.paginationWithoutLogin(
                owIssueDeclareDto,pageDto,
                OwIssueDeclare.class,
                OwIssueDeclareDto.class,
                owIssueDeclareMapper,
                false,null);

        return result;
    }

    /**
    * 分布查询，有数据边界控制功能
    * @param owIssueDeclareDto
    * @param pageDto
    * @param paramMap
    * @return
    */
    @Override
    public Result<OwIssueDeclareDto> pagination(OwIssueDeclareDto owIssueDeclareDto,PageDto pageDto,Map<String,Object> paramMap) {
        //数据边界控制参数
        Map<String,Object> paramMap1 = dataLimitService.getLimitParam(paramMap);

        //分页查询
        Result<OwIssueDeclareDto> result = myPageUtils.pagination(
                owIssueDeclareDto,pageDto,
                OwIssueDeclare.class,
                OwIssueDeclareDto.class,
                owIssueDeclareMapper,
                paramMap1,
                false,null);

        return result;
    }


    /**
     *0：未审核；1：立案；2：暂不立案；3：再学习；4：结案。
     * 未审核：deleteflag=0&&status=0
     * 暂不立案：已处理（手动处理）deleteflag=0&&status=1
     * 立案：deleteflag=1，任务已经发起，立案时间就是任务发起时间
     * 结案：deleteflag=1，任务已经完成

     * @param owIssueDeclareDto
     * @return
     */
    @Override
    public Result<OwIssueDeclareDto> queryIssueDeclareDealList(OwIssueDeclareDto owIssueDeclareDto,PageDto pageDto) {
        Result<OwIssueDeclareDto> result = new Result();

        Result<OwIssueDeclareDto> owIssueDeclareDtoResult = this.paginationWithoutLogin(owIssueDeclareDto, pageDto);
        List<OwIssueDeclareDto> owIssueDeclareDtosList = (List<OwIssueDeclareDto>)owIssueDeclareDtoResult.getResultMap().get("rows");


        for(int i=0;i<owIssueDeclareDtosList.size();i++){
            OwIssueDeclareDto owIssueDeclareDto1 = owIssueDeclareDtosList.get(i);
            String createdate = owIssueDeclareDto1.getCreatedate();

            String issueNumber = owIssueDeclareDto1.getIssueNumber();
            String deleteflag = owIssueDeclareDto1.getDeleteflag();
            String owIssueDeclareStatus = owIssueDeclareDto1.getOwIssueDeclareStatus();


            if(deleteflag.equals("0")&&owIssueDeclareStatus.equals("0")){
                owIssueDeclareDto1.setStatus("0");
                owIssueDeclareDto1.setStateStr("未审核");

            }else if(deleteflag.equals("0")&&owIssueDeclareStatus.equals("1")){
                owIssueDeclareDto1.setStatus("2");
                owIssueDeclareDto1.setStateStr("暂不立案");


            }else if(deleteflag.equals("1")){
                List<OwTask> owTasks = owTaskMapper.selectByTaskNumber(issueNumber);

                if(owTasks.size()>0){
                    Integer owTaskStatus = owTasks.get(0).getOwTaskStatus();
                    if(owTaskStatus==0||owTaskStatus==10){
                        owIssueDeclareDto1.setStatus("1");
                        owIssueDeclareDto1.setStateStr("立案");

                    }else if(owTaskStatus==20){
                        owIssueDeclareDto1.setStatus("4");
                        owIssueDeclareDto1.setStateStr("结案");

                    }
                }else{
                    owIssueDeclareDto1.setStatus("3");
                    owIssueDeclareDto1.setStateStr("审核不通过");
                }

            }

        }

        owIssueDeclareDtoResult.setResultList(owIssueDeclareDtosList);

        return owIssueDeclareDtoResult;
    }

    // xxxx
    @Override
    public Result queryIssueDeclareDealCount(String owTaskStatusStr,String findTime,String issueNumberStr) {
        Result result = new Result();

        Map<String, Object> paramMap = new HashMap<String, Object>();

        if(!StringUtils.isNull(owTaskStatusStr)){
            String[] owTaskStatusArr = owTaskStatusStr.split(",");
            paramMap.put("owTaskStatusArr",owTaskStatusArr);

        }
        if(!StringUtils.isNull(issueNumberStr)){
            String[] issueNumberArr = issueNumberStr.split(",");
            paramMap.put("issueNumberArr",issueNumberArr);
        }
        paramMap.put("findTime",findTime);
        int i = owIssueDeclareMapper.selectIssueDeclareDealCount(paramMap);
        Map<String,Object> resultMap = new HashMap<String, Object>();
        resultMap.put("total", i);
        result.setResultMap(resultMap);

        return result.success();
    }

    // xxxxx
    @Override
    public Result queryListCount() {
        Result result = new Result();

        Map<String,Object> mapParameter = new HashMap();
        //调用mapper
        int i = owIssueDeclareMapper.selectListCount(mapParameter);

        Map<String,Object> resultMap = new HashMap<String, Object>();
        resultMap.put("total", i);
        result.setResultMap(resultMap);

        return result.success();
    }

    @Override
    public Result<OwIssueDeclareDto> selectAll() {
        Result<OwIssueDeclareDto> result = new Result();

        //排序
        PageDto pageDto = new PageDto();
        pageDto.setSortColumn("id");
        pageDto.setSortOrder("desc");
        Map<String,Object> mapParam = new HashMap<>();
        mapParam.put("page",pageDto);

        List<OwIssueDeclare> list = owIssueDeclareMapper.selectAll(mapParam);
        List<OwIssueDeclareDto> dtoList = myMapper.map(list, OwIssueDeclareDto.class);
        result.setResultList(dtoList);

        return result.success();
    }

    @Override
    public Result<OwIssueDeclareDto> selectById(long id) {
        Result<OwIssueDeclareDto> result = new Result();

        OwIssueDeclare owIssueDeclare = owIssueDeclareMapper.selectById(id);
        OwIssueDeclareDto dto = mapper.map(owIssueDeclare,OwIssueDeclareDto.class);
        result.setResultObj(dto);

        return result.success();
    }


    /**
        返回ID值
    */
    @Override
    public Result<OwIssueDeclareDto> addData(OwIssueDeclareDto owIssueDeclareDto){
        Result<OwIssueDeclareDto> result = new Result();

        //封闭数据
        OwIssueDeclare owIssueDeclare = mapper.map(owIssueDeclareDto, OwIssueDeclare.class);
        owIssueDeclare.setCreatedate(DateTool.getCurTimestamp());

        //调用mapper
        long i = owIssueDeclareMapper.insert(owIssueDeclare);
        if(i==0){
            return result.fault("插入失败");
        }

        //插入多张图片
        if(owIssueDeclareDto!=null && owIssueDeclareDto.getOwPictureMagDtoList()!=null) {
            for (OwPictureMagDto owPictureMagDto : owIssueDeclareDto.getOwPictureMagDtoList()) {
                OwPictureMag owPictureMag = mapper.map(owPictureMagDto, OwPictureMag.class);
                //1:front, 2:back （默认设1）
                owPictureMag.setFrontBackSort(
                        StringUtils.isNull(owPictureMagDto.getFrontBackSort())?1:Integer.parseInt(owPictureMagDto.getFrontBackSort()));
                owPictureMag.setOwTableType("ow_issue_declare_id");
                owPictureMag.setOwTableId(owIssueDeclare.getId());
                owPictureMag.setCompanyId(0);
                owPictureMag.setCreatemanId(0);
                owPictureMag.setModifymanId(0);
                owPictureMag.setCreatedate(DateTool.getCurTimestamp());
                owPictureMagMapper.insert(owPictureMag);
            }
        }

        OwIssueDeclareDto dto = mapper.map(owIssueDeclare,OwIssueDeclareDto.class);
        result.setResultObj(dto);

        //加入执勤记录中
        OwExecuteRecord owExecuteRecord = new OwExecuteRecord();
        owExecuteRecord.setBusinessTableId(owIssueDeclare.getId());
        owExecuteRecord.setBusinessTableName("ow_issue_declare");
        owExecuteRecord.setCreateman(owIssueDeclare.getCreateman());
        owExecuteRecord.setCreatedate(owIssueDeclare.getCreatedate());
        owExecuteRecord.setCompanyId(owIssueDeclare.getCompanyId());
        owExecuteRecord.setCreatemanId(owIssueDeclare.getCreatemanId());
        owExecuteRecord.setModifymanId(owIssueDeclare.getModifymanId());
        owExecuteRecordMapper.insert(owExecuteRecord);

        return result.success();
    }

    /**
        返回ID值
    */
    @Override
    public Result<OwIssueDeclareDto> addEditData(OwIssueDeclareDto owIssueDeclareDto){
        OwIssueDeclare owIssueDeclare = new OwIssueDeclare();
        owIssueDeclare.setIssueNumber(owIssueDeclareDto.getIssueNumber());
        Map<String,Object> mapParam = new HashMap<>();
        mapParam.put("bean",owIssueDeclare);
        List<OwIssueDeclare> owIssueDeclareList = owIssueDeclareMapper.selectByPagination(mapParam);
        if(owIssueDeclareList==null || owIssueDeclareList.size()==0){
            //添加数据
            return addData(owIssueDeclareDto);
        }else{
            //修改数据
            OwIssueDeclare owIssueDeclare1 = owIssueDeclareList.get(0);
            owIssueDeclareDto.setId(""+owIssueDeclare1.getId());
            return editData(owIssueDeclareDto);
        }
    }




    /**
        返回ID值
    */
    @Override
    public Result<OwIssueDeclareDto> editData(OwIssueDeclareDto owIssueDeclareDto){
        Result<OwIssueDeclareDto> result = new Result();

        //封装数据
        OwIssueDeclare owIssueDeclare = mapper.map(owIssueDeclareDto, OwIssueDeclare.class);
        owIssueDeclare.setModifydate(DateTool.getCurTimestamp());

        //调用mapper
        long i = owIssueDeclareMapper.updateById(owIssueDeclare);
        if(i==0){
            return result.fault("编辑数据失败");
        }

        //插入多张图片
        if(owIssueDeclareDto!=null && owIssueDeclareDto.getOwPictureMagDtoList()!=null) {
            //有新图片时，把老图片删除了；没有新图片的话，先别删除
            if(owIssueDeclareDto.getOwPictureMagDtoList().size()>0){
                //.out.println("=====>owIssueDeclare.getId():"+owIssueDeclare.getId());
                List<OwPictureMag> owPictureMagList = owPictureMagMapper.selectPictureByOwIssueDeclareId(owIssueDeclare.getId());
                Map<String,Object> delMap = new HashMap<>();
                delMap.put("modifyman","system");
                delMap.put("modifydate",DateTool.getCurTimestamp());
                for(OwPictureMag owPictureMag : owPictureMagList) {
                    delMap.put("id",owPictureMag.getId());
                    owPictureMagMapper.deleteById(delMap);
                }
            }
            for (OwPictureMagDto owPictureMagDto : owIssueDeclareDto.getOwPictureMagDtoList()) {
                OwPictureMag owPictureMag = mapper.map(owPictureMagDto, OwPictureMag.class);
                //1:front, 2:back （默认设1）
                owPictureMag.setFrontBackSort(
                        StringUtils.isNull(owPictureMagDto.getFrontBackSort())?1:Integer.parseInt(owPictureMagDto.getFrontBackSort()));
                owPictureMag.setOwTableType("ow_issue_declare_id");
                owPictureMag.setOwTableId(owIssueDeclare.getId());
                owPictureMag.setCompanyId(0);
                owPictureMag.setCreatemanId(0);
                owPictureMag.setModifymanId(0);
                owPictureMag.setCreatedate(DateTool.getCurTimestamp());
                owPictureMagMapper.insert(owPictureMag);
            }
        }

        OwIssueDeclareDto dto = mapper.map(owIssueDeclare, OwIssueDeclareDto.class);
        result.setResultObj(dto);

        return result.success();
    }

    /**
    伪删除记录，返回ID值
    */
    @Override
    public Result deleteById(long id,String adminMan){
        Result result = new Result();

        Map<String,Object> mapParameter = new HashMap();
        mapParameter.put("id", id);
        mapParameter.put("modifyman",adminMan);
        mapParameter.put("modifydate",DateTool.getCurTimestamp());

        //调用mapper
        long i = owIssueDeclareMapper.deleteById(mapParameter);
        if(i==0){
            return result.fault("删除数据失败");
        }

        return result.success();
    }





    /**
     *页面上查询列的值，动态加载，sql语句读数据库配置而来
     */
    public java.util.List select4a2userId(){
        return owIssueDeclareMapper.select4a2userId();
    }




}
